package com.alisms.utils;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Component
public class UpdatePasswordAliSMS {

    private static final Logger log = LoggerFactory.getLogger(UpdatePasswordAliSMS.class);


    private static final String smsDomain = "dysmsapi.aliyuncs.com";
    private static final String accessKeyId = "LTAI4G5FaFLD4MUFFvNJKy7X";
    private static final String accessSecret = "mLbfGQPe70Pi1Zbd34Wm1nkmAiSxu8";
    private static final String signName = "水发智能物联有限公司";
    //找回密码模板
    private static final String templateCode = "SMS_201230314";


    /**
     * 发送短信
     *
     * @param phone 手机号
     * @param param 模板参数
     * @param 模板号
     * @return
     */
    public boolean send(String phone, Map param) {

        DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(smsDomain);
        request.setAction("SendSms");
        request.setVersion("2017-05-25");
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("TemplateCode", templateCode);
        //   JSON.toJSON()
        String jsonParam = JSON.toJSONString(param);
        request.putQueryParameter("TemplateParam", jsonParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            Map<String, Object> map = JSON.parseObject(data, HashMap.class);
            String res = (String) map.get("Code");
            if (!"OK".equals(res)) {
                log.error("短信发送失败:{}", data);
                return false;
            }
        } catch (ServerException e) {
            log.error("短信发送失败:{}", e.getMessage());
            e.printStackTrace();
        } catch (ClientException e) {
            log.error("短信发送失败:{}", e.getMessage());
            e.printStackTrace();
        }
        return true;
    }

}
